/**
 * 批量操作Hook
 * 管理批量操作的逻辑和状态验证
 */

import { useCallback } from 'react';
import { RoomStatus } from '../../../types/room';
import { useRoomStateManager } from './useRoomStateManager';
import { RoomStatusManager } from '../utils/RoomStatusManager';
import type { BatchOperation } from '../components/BatchOperationMenu';
import type { Room } from '../../../types/room';

export interface BatchOperationResult {
  success: boolean;
  updatedCount: number;
  skippedCount: number;
  errors: string[];
  details: {
    roomId: string;
    date: string;
    success: boolean;
    error?: string;
    originalStatus?: RoomStatus;
    newStatus?: RoomStatus;
  }[];
}

export interface UseBatchOperationsReturn {
  // 执行批量操作
  executeBatchOperation: (
    operation: BatchOperation,
    cells: {
      roomId: string;
      date: string;
      roomIndex: number;
      dateIndex: number;
    }[],
    rooms: Room[]
  ) => Promise<BatchOperationResult>;

  // 验证批量操作
  validateBatchOperation: (
    operation: BatchOperation,
    cells: {
      roomId: string;
      date: string;
      roomIndex: number;
      dateIndex: number;
    }[]
  ) => {
    canProceed: boolean;
    warnings: string[];
    conflicts: { roomId: string; date: string; reason: string }[];
  };

  // 获取操作预览
  getOperationPreview: (
    operation: BatchOperation,
    cells: {
      roomId: string;
      date: string;
      roomIndex: number;
      dateIndex: number;
    }[]
  ) => {
    totalCells: number;
    validCells: number;
    invalidCells: number;
    statusChanges: Map<RoomStatus, number>;
  };
}

export const useBatchOperations = (): UseBatchOperationsReturn => {
  const stateManager = useRoomStateManager();

  // 执行批量操作
  const executeBatchOperation = useCallback(
    async (
      operation: BatchOperation,
      cells: {
        roomId: string;
        date: string;
        roomIndex: number;
        dateIndex: number;
      }[],
      rooms: Room[]
    ): Promise<BatchOperationResult> => {
      const result: BatchOperationResult = {
        success: true,
        updatedCount: 0,
        skippedCount: 0,
        errors: [],
        details: [],
      };

      // 准备批量更新数据
      const updates: { roomId: string; date: string; status: RoomStatus }[] =
        [];

      // 处理每个单元格
      for (const cell of cells) {
        const { roomId, date } = cell;

        // 调试信息
        console.log('处理单元格:', { roomId, date, cell });

        const room = rooms.find(r => r.id === roomId);

        if (!room) {
          console.error('房间查找失败:', {
            roomId,
            date,
            availableRoomIds: rooms.map(r => ({
              id: r.id,
              number: r.roomNumber,
            })),
            cell,
          });

          result.details.push({
            roomId,
            date,
            success: false,
            error: `房间不存在 (ID: ${roomId})`,
          });
          result.errors.push(
            `房间 ${roomId} 不存在，可用房间: ${rooms.map(r => r.roomNumber).join(', ')}`
          );
          result.skippedCount++;
          continue;
        }

        try {
          // 获取当前状态
          const currentStatus = stateManager.getRoomStatus(roomId, date);

          // 验证状态转换
          const canTransition = validateStatusTransition(
            currentStatus,
            operation.targetStatus
          );

          if (!canTransition.valid) {
            result.details.push({
              roomId,
              date,
              success: false,
              error: canTransition.reason,
              originalStatus: currentStatus || RoomStatus.AVAILABLE,
            });
            result.skippedCount++;
            continue;
          }

          // 添加到批量更新列表
          updates.push({
            roomId,
            date,
            status: operation.targetStatus,
          });

          result.details.push({
            roomId,
            date,
            success: true,
            originalStatus: currentStatus || RoomStatus.AVAILABLE,
            newStatus: operation.targetStatus,
          });
          result.updatedCount++;
        } catch (error) {
          const errorMessage =
            error instanceof Error ? error.message : '未知错误';
          result.details.push({
            roomId,
            date,
            success: false,
            error: errorMessage,
            originalStatus:
              stateManager.getRoomStatus(roomId, date) || RoomStatus.AVAILABLE,
          });
          result.errors.push(
            `房间 ${room.roomNumber} (${date}): ${errorMessage}`
          );
          result.skippedCount++;
        }
      }

      // 执行批量更新
      if (updates.length > 0) {
        try {
          stateManager.batchUpdateStatus(updates);
          console.log(`🎯 批量操作成功: ${operation.label}`, {
            更新数量: result.updatedCount,
            跳过数量: result.skippedCount,
            目标状态: operation.targetStatus,
          });
        } catch (error) {
          result.success = false;
          result.errors.push(`批量更新失败: ${error}`);
        }
      }

      // 如果有错误，标记为失败
      if (result.errors.length > 0) {
        result.success = false;
      }

      return result;
    },
    [stateManager]
  );

  // 验证批量操作
  const validateBatchOperation = useCallback(
    (
      operation: BatchOperation,
      cells: {
        roomId: string;
        date: string;
        roomIndex: number;
        dateIndex: number;
      }[]
    ) => {
      const warnings: string[] = [];
      const conflicts: { roomId: string; date: string; reason: string }[] = [];

      // 检查每个单元格
      cells.forEach(cell => {
        const currentStatus = stateManager.getRoomStatus(
          cell.roomId,
          cell.date
        );
        const validation = validateStatusTransition(
          currentStatus,
          operation.targetStatus
        );

        if (!validation.valid) {
          conflicts.push({
            roomId: cell.roomId,
            date: cell.date,
            reason: validation.reason,
          });
        }
      });

      // 生成警告信息
      if (conflicts.length > 0) {
        warnings.push(`${conflicts.length} 个单元格无法执行此操作`);
      }

      const canProceed = conflicts.length < cells.length; // 只要有部分可以执行就允许

      return {
        canProceed,
        warnings,
        conflicts,
      };
    },
    [stateManager]
  );

  // 获取操作预览
  const getOperationPreview = useCallback(
    (
      operation: BatchOperation,
      cells: {
        roomId: string;
        date: string;
        roomIndex: number;
        dateIndex: number;
      }[]
    ) => {
      const statusChanges = new Map<RoomStatus, number>();
      let validCells = 0;
      let invalidCells = 0;

      cells.forEach(cell => {
        const currentStatus =
          stateManager.getRoomStatus(cell.roomId, cell.date) ||
          RoomStatus.AVAILABLE;
        const validation = validateStatusTransition(
          currentStatus,
          operation.targetStatus
        );

        if (validation.valid) {
          validCells++;
          statusChanges.set(
            currentStatus,
            (statusChanges.get(currentStatus) || 0) + 1
          );
        } else {
          invalidCells++;
        }
      });

      return {
        totalCells: cells.length,
        validCells,
        invalidCells,
        statusChanges,
      };
    },
    [stateManager]
  );

  return {
    executeBatchOperation,
    validateBatchOperation,
    getOperationPreview,
  };
};

// 状态转换验证辅助函数
function validateStatusTransition(
  currentStatus: RoomStatus | null,
  targetStatus: RoomStatus
): { valid: boolean; reason: string } {
  const current = currentStatus || RoomStatus.AVAILABLE;

  // 定义允许的状态转换规则
  const transitionRules: Record<RoomStatus, RoomStatus[]> = {
    [RoomStatus.AVAILABLE]: [
      RoomStatus.BOOKED,
      RoomStatus.CLEANING,
      RoomStatus.MAINTENANCE,
      RoomStatus.OUT_OF_ORDER,
    ],
    [RoomStatus.BOOKED]: [
      RoomStatus.OCCUPIED,
      RoomStatus.AVAILABLE, // 取消预订
      RoomStatus.MAINTENANCE,
    ],
    [RoomStatus.OCCUPIED]: [RoomStatus.CHECKED_OUT, RoomStatus.MAINTENANCE],
    [RoomStatus.CHECKED_OUT]: [
      RoomStatus.CLEANING,
      RoomStatus.AVAILABLE,
      RoomStatus.MAINTENANCE,
    ],
    [RoomStatus.CLEANING]: [
      RoomStatus.CLEANED,
      RoomStatus.AVAILABLE,
      RoomStatus.MAINTENANCE,
    ],
    [RoomStatus.CLEANED]: [RoomStatus.AVAILABLE, RoomStatus.MAINTENANCE],
    [RoomStatus.MAINTENANCE]: [RoomStatus.AVAILABLE],
    [RoomStatus.OUT_OF_ORDER]: [RoomStatus.MAINTENANCE, RoomStatus.AVAILABLE],
    // 其他状态的默认规则
    [RoomStatus.PARTIALLY_BOOKED]: [RoomStatus.BOOKED, RoomStatus.AVAILABLE],
    [RoomStatus.VIP_BOOKED]: [RoomStatus.OCCUPIED, RoomStatus.AVAILABLE],
    [RoomStatus.DIRTY]: [RoomStatus.CLEANING, RoomStatus.AVAILABLE],
    [RoomStatus.DEEP_CLEANING]: [RoomStatus.CLEANED, RoomStatus.AVAILABLE],
    [RoomStatus.INSPECTING]: [RoomStatus.AVAILABLE, RoomStatus.MAINTENANCE],
    [RoomStatus.ROUTINE_MAINTENANCE]: [RoomStatus.AVAILABLE],
    [RoomStatus.DEEP_MAINTENANCE]: [RoomStatus.AVAILABLE],
    [RoomStatus.REPAIR]: [RoomStatus.AVAILABLE],
    [RoomStatus.EQUIPMENT_REPLACEMENT]: [RoomStatus.AVAILABLE],
    [RoomStatus.LOCKED]: [RoomStatus.AVAILABLE],
    [RoomStatus.TEMPORARILY_UNAVAILABLE]: [RoomStatus.AVAILABLE],
  };

  // 如果目标状态与当前状态相同，跳过
  if (current === targetStatus) {
    return { valid: false, reason: '状态无需更改' };
  }

  // 检查是否允许转换
  const allowedTransitions = transitionRules[current] || [];
  const isAllowed = allowedTransitions.includes(targetStatus);

  if (!isAllowed) {
    const currentConfig = RoomStatusManager.getStatusConfig(current);
    const targetConfig = RoomStatusManager.getStatusConfig(targetStatus);
    return {
      valid: false,
      reason: `无法从"${currentConfig.label}"转换为"${targetConfig.label}"`,
    };
  }

  return { valid: true, reason: '' };
}

export default useBatchOperations;
